<template>
  <view class="uni-container food-product-list">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="type_id" label="所属分类"  class="alignFlexStart" required>
        <div v-if="type_id_localdata.length>0">
          <uni-data-checkbox mode="button" v-model="formData.type_id" :localdata="type_id_localdata"></uni-data-checkbox>
        </div>
        <div v-else class="noCheckboxData">
            当前没有任何数据
        </div>
      </uni-forms-item>
      <uni-forms-item name="product_name" label="商品名称" required>
        <uni-easyinput placeholder="请输入商品名称，2-20位组成" v-model="formData.product_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="product_base_price" label="商品基础价格" required>
        <uni-easyinput placeholder="请输入商品基础价格，单位元" :maxlength="4" type="number" v-model="formData.product_base_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="product_icon" label="商品图片" class="alignFlexStart" required>
        <uni-file-picker ref="files" @select="(e)=>fileList=e" @delete="()=>fileList==null" :auto-upload="false" file-mediatype="image" file-extname="jpg,png" :limit="1" return-type="array" v-model="formData.product_icon"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="product_inventory" label="价格库存信息"  class="alignFlexStart" required>
        <div class="product_inventory_box">
            <div v-if="product_inventory_list.length>0">

              <uni-table :border="true" :stripe="true" emptyText="请至少添加一列价格库存信息" >
                  <uni-tr>
                    <uni-th align="center">规格类型</uni-th>
                    <uni-th align="center">规格名称</uni-th>
                    <uni-th width="110" align="center">份量（份）</uni-th>
                    <uni-th width="110" align="center">起购（份）</uni-th>
                    <uni-th width="100" align="center">基础费用</uni-th>
                    <uni-th width="100" align="center">附加费用</uni-th>
                    <uni-th width="100" align="center">重量</uni-th>
                    <uni-th width="100" align="center">库存</uni-th>
                    <uni-th width="100" align="center">默认选中</uni-th>
                    <uni-th width="100" align="center">删除本行</uni-th>
                  </uni-tr>
                  <uni-tr v-for="(it,i) in product_inventory_list" :key="i">
                    <uni-td>
                      <div class="flexStyle">
                        <uni-easyinput :errorMessage="it.label_type.error" v-model="it.label_type.value" placeholder="请输入" :trim="true" :maxlength="8" class="myFontSize" :clearable="false" style="width:110px" ></uni-easyinput>
                      </div>
                    </uni-td> 
                    <uni-td>
                      <div class="flexStyle">
                        <uni-easyinput :errorMessage="it.label_name.error" v-model="it.label_name.value" placeholder="请输入" :trim="true" :maxlength="15" class="myFontSize" :clearable="false" style="width:110px"></uni-easyinput>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle">
                        <uni-easyinput :errorMessage="it.spec_count.error" v-model="it.spec_count.value" placeholder="请输入" :trim="true" :maxlength="4" type="number" class="myFontSize" :clearable="false" style="width:60px;flex: inherit;"></uni-easyinput>
                        <div class="tipsText" style="margin-left:3px">人份</div>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle">
                        <uni-easyinput :errorMessage="it.min_spec_count.error" v-model="it.min_spec_count.value" placeholder="请输入" :trim="true" :maxlength="4" type="number" class="myFontSize" :clearable="false" style="width:60px;flex: inherit;"></uni-easyinput>
                        <div class="tipsText" style="margin-left:3px">份起</div>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle">
                        <uni-easyinput  v-model="formData.product_base_price" :disabled="true" :inputBorder="false" :trim="true" type="number" class="myFontSize" :clearable="false" style="width:60px;flex: inherit;"></uni-easyinput>
                        <div class="tipsText" style="margin-left:3px">元</div>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle">
                        <uni-easyinput :errorMessage="it.price.error" v-model="it.price.value" placeholder="请输入" :maxlength="4" :trim="true" type="number" class="myFontSize" :clearable="false" style="width:60px;flex: inherit;"></uni-easyinput>
                        <div class="tipsText" style="margin-left:3px">元</div>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle">
                        <div class="tipsText" style="margin-right:3px">约</div>
                        <uni-easyinput :errorMessage="it.weight.error" v-model="it.weight.value" placeholder="请输入" :maxlength="4" :trim="true" type="number" class="myFontSize" :clearable="false" style="width:60px;flex: inherit;"></uni-easyinput>
                        <div class="tipsText" style="margin-left:3px">克</div>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle">
                        <uni-easyinput :errorMessage="it.stock.error" v-model="it.stock.value" placeholder="请输入" :maxlength="4" :trim="true" type="number" class="myFontSize" :clearable="false" style="width:60px;flex: inherit;"></uni-easyinput>
                        <div class="tipsText" style="margin-left:3px">份</div>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle">
                        <switch :checked="it.default_checked" @change="switchChange($event,i)" color="#FFCC33" style="transform:scale(0.7)"/>
                      </div>
                    </uni-td>
                    <uni-td>
                      <div class="flexStyle" v-if="product_inventory_list.length>1">
                        <uni-icons type="clear" size="28" class="clearIcon" @click="doProductLine('remove',i)"></uni-icons>
                      </div>
                    </uni-td> 
                  </uni-tr>
                </uni-table>

              <div class="flexAc addSelectBox" @click="doProductLine('add')" v-if="product_inventory_list.length<15">
                  <uni-icons type="plusempty" size="17" color="#2979ff"></uni-icons>
                  <div>添加更多规格</div>
              </div>
            </div>
        </div>
      </uni-forms-item>
    <uni-forms-item name="product_status" label="商品状态" required>
        <uni-data-checkbox mode="button" v-model="formData.product_status" :localdata="formOptions.product_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="product_lable" label="商品标签" required>
        <uni-data-checkbox mode="button" v-model="formData.product_lable" :localdata="formOptions.product_lable_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="product_discount" label="商品打折">
        <uni-data-checkbox  mode="button"  v-model="selectIndex" :localdata="selectList"></uni-data-checkbox>
        <div class="flexStyle mySelectBox" v-if="selectIndex==1">
          <select class="mySelect" v-model="discountValue[0]" style="width:32px;padding:0">
              <option :value="it" v-for="(it,i) in 9" :key="i">{{it}}</option>
          </select>
          <div style="margin:0 3px">-</div>
            <select class="mySelect" v-model="discountValue[1]" style="width:32px;padding:0;">
              <option :value="i" v-for="(it,i) in 10" :key="i">{{i}}</option>
          </select>
          <div style="margin-left:10rpx">折</div>
        </div>
      </uni-forms-item>
      <uni-forms-item name="product_sort" label="商品排行">
        <uni-easyinput placeholder="在分类目录下下，值越大越往后" type="number" v-model="formData.product_sort"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="product_description" label="商品描述">
        <uni-easyinput type="textarea" :maxlength="500" placeholder="请输入商品描述（选填）" v-model="formData.product_description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <lay-button type="normal" @click="submit">确认提交</lay-button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <lay-button>取消关闭</lay-button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<style lang="stylus" scoped>
.noCheckboxData
  height: 150rpx
  display: flex
  width 100%
  align-items: center
  justify-content: center
  font-size: 22rpx
  color: rgb(119, 119, 119)
  user-select: none
.product_inventory_box
  .tipsText
    font-size: 12px
  .addSelectBox
    font-size: 22rpx
    margin-top: 15rpx
    cursor pointer
    user-select: none
    color: #2979ff
  .clearIcon
    cursor pointer
    &:hover
      color: #007aff !important
</style>

<script>
  import { validator } from '../../js_sdk/validator/food-product-list.js';
  import {getDataType,deepClone} from '@/utils/helper.js'
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food-product-list';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

function createProductLineInfo(){
  return {
    id:{
      error:false,
      value:+new Date(),
      type:`[object Number]`
    },
    label_type:{
      error:false,
      value:``,
      type:`[object String]`
    },
    label_name:{
      error:false,
      value:``,
      type:`[object String]`
    },
    spec_count:{
      error:false,
      value:1,
      type:`[object Number]`,
      typeVerify:(value)=>(/^\d+$/.test(value+''.trim()))
    },   //1人份
    min_spec_count:{
      error:false,
      value:1,
      type:`[object Number]`,
      typeVerify:(value)=>(/^\d+$/.test(value+''.trim()))
    },     //几份起购
    price:{
      error:false,
      value:0,
      type:`[object Number]`,
      typeVerify:(value)=>(/^\d+(\.\d+)?$/.test(value+''.trim()))
    },        //单价
    weight:{
      error:false,
      value:``,
      type:`[object Number]`
    },     //重量
    stock:{
      error:false,
      value:9999,
      type:`[object Number]`,
      typeVerify:(value)=>(/^\d+$/.test(value+''.trim()))
    },     //库存
    default_checked:false,  //默认选中
  }
}


  

  export default {
    data() {
      let formData = {
        "merchant_id": store.userInfo.merchant_id,
        "type_id": "",
        "product_name": "",
        "product_base_price": null,
        "product_discount": 0,
        "product_icon": [],
        "product_inventory": [],
        "product_status": 0,
        "product_lable": 0,
        "product_sort": 1,
        "product_description": ""
      }
      return {
        fileList:null,
        type_id_localdata:[],
        product_inventory_list:[createProductLineInfo()],
        selectIndex:0,
        selectList:[{
          text: '不打折',
					value: 0
        },{
          text: '要打折',
					value: 1
        }],
        discountValue:[9,0],
        
        formData,
        formOptions: {
          "product_status_localdata": [
            {
              "text": "正在热销",
              "value": 0
            },
            {
              "text": "暂停停售",
              "value": 1
            },
            {
              "text": "样品展示",
              "value": 2
            }
          ],
          "product_lable_localdata": [
            {
              "text": "普通",
              "value": 0
            },
            {
              "text": "新品",
              "value": 1
            },
            {
              "text": "招牌",
              "value": 2
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    watch:{
      discountValue:{
        handler:function(val){
          this.formData.product_discount=Number(val.join('.'))
        }
      },
      selectIndex:{
        handler:function(val){
          if(val==0){
            this.formData.product_discount=0;
          }else{
            this.formData.product_discount=Number(this.discountValue.join('.'))
          }
        },
        immediate:true
      },
      'formData.merchant_id':{
        handler:async function(val){
          this.type_id_localdata=[];
          const merchant_id=val.trim();
          if(merchant_id!=''){
              const {result:{data}}= await db.collection(`food-store-types`).where({merchant_id,type_status:true}).field(`type_name`).get();
              this.type_id_localdata=data.map(it=>{
                return {
                  text:it.type_name,
                  value:it._id
                }
              })
          }

          if(this.type_id_localdata.length===0){
            this.formData.type_id=``;
          }
        },
        immediate:true
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules);
    },
    methods: {
        doProductLine(type,index){
        if(type===`add`){
          this.product_inventory_list.push(createProductLineInfo())
        }else{
          this.product_inventory_list.splice(index,1);
        }
      },
      switchChange({detail:{value}},index){
        const it=this.product_inventory_list[index];
        this.product_inventory_list.splice(index,1,{
          ...it,
          default_checked:value
        })
      },
      productInventoryKeyVerify(key){

      },
      productInventoryVerify(){

        let [forMatData,isError,errorText]=[[],false,`价格库存信息填写错误，请重新填写`];
      const resetList=deepClone(this.product_inventory_list);
      resetList.map(it=>{
        for(let key in it){
          const obj=it[key]
          if(getDataType(obj)===`[object Object]`){
            it[key]={
              ...obj,
              error:false
            }
          }
        }
      })
      this.product_inventory_list=resetList

        const inventorylist=this.product_inventory_list;
        for(let i=0;i<inventorylist.length;i++){
          const it=inventorylist[i];
            for(let [key,obj] of Object.entries(it)){
              if(getDataType(obj)===`[object Object]`){
                const {value,type,typeVerify}=obj;
                if(value===``){
                  it[key]={
                    ...obj,
                    error:true
                  }
                  this.product_inventory_list.splice(i,1,it)
                  isError=true;
                  continue
                }
              if(getDataType(value,true)!==type){
                  it[key]={
                    ...obj,
                    error:true
                  }
                  this.product_inventory_list.splice(i,1,it)
                  isError=true;
                  continue
                }
                if(typeVerify){
                  if(!typeVerify(value)){
                    it[key]={
                      ...obj,
                      error:true
                    }
                    this.product_inventory_list.splice(i,1,it)
                    isError=true;
                    continue
                  }
                }
              }
            }
        }

        if(!isError){
            const createTypes=this.product_inventory_list;
            const typesObj={};
            createTypes.map(it=>{
              const values={};
              const typeName=it.label_type.value.trim();

              for(let key in it){
                const val=it[key];
                const type=getDataType(val);
                if(type===`[object Object]`){
                  let finallyValue=val.value
                  if(!isNaN(val.value)){
                    finallyValue=parseFloat(val.value)
                  }
                  values[key]=finallyValue;
                }else{
                  values[key]=val;
                }
              }
              if(typesObj[typeName]==null){
                typesObj[typeName]=[];
              }
              typesObj[typeName].push(values)
            })
            const tipsTypeList=[];
            const emptyList=[]
            for(let key in typesObj){
              let selectCount=0;
              typesObj[key].map(it=>{
                if(it.default_checked){
                  selectCount++
                }
              })
              if(selectCount>1){
                tipsTypeList.push(key)
              }else if(selectCount==0){
                emptyList.push(key)
              }
              forMatData.push({
                name:key,
                values:typesObj[key]
              })
            }
            errorText=``;
            if(tipsTypeList.length>0){
              errorText+=`规格类型为：${tipsTypeList.join(',')}，每个类型只能默认选中一项`
              isError=true
            }
            if(emptyList.length>0){
              if(errorText!=''){
                errorText+=`\r\n`
              }
              errorText+=`规格类型为：${emptyList.join(',')}，必须选择一项为默认选中`
              isError=true
            }

        }


        return {isError,errorText,forMatData}
      },

      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })

        const {isError,errorText,forMatData} =this.productInventoryVerify();

        this.$refs.form.validate().then(async (res) => {

          if(this.fileList==null){
              return layer.msg(`请务必上传商品图片`, { icon : 2, time: 2000})
            }
            
            if(isError){
              return layer.msg(errorText, { icon : 2, time: 2000})
            }

            if(forMatData.length<1){
              return layer.msg(`价格库存信息至少需要设置一条`, { icon : 2, time: 2000})
            }
            res.product_inventory=forMatData
            res.product_icon= await this.$refs.files.upload();
            res.merchant_id=store.userInfo.merchant_id

          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
